<template>
  <edit-dialog :centerDialogVisible="visible" :tilte="tilte" :default-button="false" @Cancel="handlerCancel"
      @Submit="handlerAddSubmit" :width="width">
    <template #content>
      <div style="height: 480px;overflow-y: auto;overflow-x: hidden;">
        <el-form ref="addGoodsFormRef" :model="addForm" :rules="rules" label-position="right" label-width="120px"
          :inline="true">
          <el-form-item label="物品名称：" prop="goodsName" >
            <el-input maxlength="50" placeholder="请输入物品名称" v-model.trim="addForm.goodsName" clearable  />
          </el-form-item>
          <el-form-item label="物品类型：" prop="goodsType">
            <el-select v-model="addForm.goodsType" placeholder="请选择"  @change="handlerGoodsTypeChange">
                <el-option v-for="item in goodsType" :label="item.goodsType" :value="item.typeId" :key="item.typeId" />
              </el-select>
          </el-form-item>
          <el-form-item label="捡拾日期：" prop="pickUpTime">
            <el-date-picker v-model="addForm.pickUpTime" placeholder="请选择捡拾日期" type="datetime" @change="handlerPickDateChange" />
          </el-form-item>
          <el-form-item label="保质期：" prop="timeLimit">
            <el-input v-model="addForm.timeLimit"  @change="handlerPickDateChange">
              <template #append>
                <el-select v-model="addForm.timeLimitUnit" placeholder="请选择" style="width: 90px" @change="handlerPickDateChange">
                  <el-option label="小时" value="H" />
                  <el-option label="天" value="D" />
                  <el-option label="年" value="Y" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="物品时效：" prop="goodsLimitTime">
            <el-date-picker  :disabled="disabled" placeholder="请输入物品时效" v-model="addForm.goodsLimitTime" type="datetime"  />
          </el-form-item>
          <el-form-item label="捡拾人姓名：" prop="pickUpName">
            <el-input maxlength="16" v-model.trim="addForm.pickUpName" placeholder="请输入捡拾人姓名"/>
          </el-form-item>
          <el-form-item label="捡拾人电话：" prop="pickUpPhone">
            <el-input maxlength="15" v-model.trim="addForm.pickUpPhone" placeholder="请输入捡拾人电话"/>
          </el-form-item>
          <el-form-item label="航站楼[捡拾]：" prop="pickUpTerminal">
            <el-select v-model.trim="addForm.pickUpTerminal" placeholder="请选择" >
              <el-option v-for="item in terminal" :label="item.label" :value="item.value" :key="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="捡拾地：" prop="pickUpPlace">
            <el-input maxlength="20" v-model.trim="addForm.pickUpPlace" placeholder="请输入捡拾地" />
          </el-form-item>
          <el-form-item label="航站楼[存放]：" prop="depositTerminal">
            <el-select v-model.trim="addForm.depositTerminal" placeholder="请选择" >
              <el-option v-for="item in terminal" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="存放地：" prop="depositPlace">
            <el-select v-model.trim="addForm.depositPlace" placeholder="请选择" >
              <el-option v-for="item in depositPlace" :label="item.name" :value="item.key" :key="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item v-if=" addForm.depositPlace === 'lose_deposit_place_2'" label="入库位置：" prop="place">
            <el-input v-model.trim="addForm.place" placeholder="请输入入库位置" />
          </el-form-item>
          <br />
          <el-form-item label="图片：" class="upload-img">
            <el-upload ref="uploadRef" v-model:file-list="fileList" :action="baseUrlConfig.businessBaseUrl+'/fast/uploadFile'"
              list-type="picture-card"
              :on-success="handlerUploadSuccess"
              :on-error="handlerUploadError"
              :on-preview="handlePictureCardPreview"
              :before-upload="handlerBeforeUpload"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
              limit="10"
              :class="{ hide : hideUpload}">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #custom>
      <span class="dialog-footer">
        <el-button class="buttonCancel" @click="handlerCancel">返回</el-button>
        <el-button class="buttonReceive" @click="handlerAddSubmit(addGoodsFormRef)" :loading="loading">确定</el-button>
      </span>
    </template>
  </edit-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, defineProps, computed, watch } from 'vue'
import { useStore } from 'vuex'
import { dayjs, FormInstance, FormRules, UploadProps, UploadUserFile } from 'element-plus'
import editDialog from '@/components/editDialog/index.vue'
import { ElMessage } from 'element-plus'
import { AppendGoodsItem, pickUpGoodsAppend } from '@/api/lose/goodsReg'
import { deleteFile } from '@/api/common'
import { fa } from 'element-plus/es/locale'
import {uploadFiles} from "@/api/common";
import {baseUrlConfig} from '@/config/config'


interface RuleForm {
  goodsName: string;
  goodsType: string;
  pickUpTime: string;
  timeLimit: number;
  timeLimitUnit: string;
  goodsLimitTime: string;
  pickUpName: string;
  pickUpPhone: string;
  pickUpTerminal: string;
  pickUpPlace: string;
  depositTerminal: string;
  depositPlace: string;
  place: string;
}
const addGoodsFormRef = ref<FormInstance>()
const uploadRef = ref()
const loading = ref(false)
const tilte = ref('新增捡拾物品')
const width = ref('770px')
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
const terminal = computed(() => store.state.terminal.data)
const depositPlace = computed(() => store.state.depositPlace.data)
const disabled = ref(false)
const hideUpload = ref(false)
const addForm = reactive<RuleForm>({
  goodsName: '',
  goodsType: '',
  pickUpTime: '',
  timeLimit: 1,
  timeLimitUnit: 'H',
  goodsLimitTime: '',
  pickUpName: '',
  pickUpPhone: '',
  pickUpTerminal: '',
  pickUpPlace: '',
  depositTerminal: '',
  depositPlace: '',
  place: ''
})

interface FileFace {
  enclosureContent: string
  enclosureName: string
  enclosureSuffix: string
  resourceAddress: string
  enclosureCode: string
}
const goodsFile = ref<Array<FileFace>>([])
const validatePhone = (rule: any, value: any, callback: any) => {
  if (!value) return callback()
  if (!/^[1][3,4,5,7,8,9][0-9]{9}$/.test(value)) return callback(new Error('手机号格式错误'))
  callback()
}
const rules = reactive<FormRules>({
  goodsName: [
    { required: true, message: '请输入物品类型名称', trigger: 'blur' },
    { max: 50, message: '最大长度50', trigger: 'blur' }
  ],
  goodsType: [
    { required: true, message: '请选择物品类型', trigger: 'blur' }
  ],
  pickUpTime: [
    { required: true, message: '请选择捡拾日期', trigger: 'blur' }
  ],
  timeLimit: [
    { required: true, message: '请输入保质期', trigger: 'blur' }
  ],
  goodsLimitTime: [
    { required: true, message: '请选择物品时效', trigger: 'blur' }
  ],
  pickUpName: [
    { required: true, message: '请输入捡拾人姓名', trigger: 'blur' }
  ],
  pickUpPhone: [
    { required: true, message: '请输入捡拾人电话', trigger: 'blur' },
    { required: true, validator: validatePhone, trigger: 'blur' },
    { max: 50, message: '最大长度50', trigger: 'blur' }
  ],
  pickUpTerminal: [
    { required: true, message: '请选择捡拾航站楼', trigger: 'blur' }
  ],
  pickUpPlace: [
    { required: true, message: '请输入捡拾地', trigger: 'blur' }
  ],
  depositTerminal: [
    { required: true, message: '请选择存放航站楼', trigger: 'blur' }
  ],
  depositPlace: [
    { required: true, message: '请输入存放地', trigger: 'blur' }
  ],
  place: [
    { required: true, message: '请输入入库位置', trigger: 'blur' }
  ]
})

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  goodsType: {
    type: Array
  }
})

const fileList = ref<UploadUserFile[]>([
  // {
  //   name: '',
  //   url: ''
  // }
])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const emit = defineEmits(['cancel', 'submit'])
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  // console.log(uploadFile, uploadFiles)
  const code = uploadFile.response?.data?.enclosureCode
  delFile(code)
  hideUpload.value = false
  const values: Array<FileFace> = []
  goodsFile.value.forEach((item, index) => {
    if (item.enclosureCode !== code) {
      values.push(item)
    }
  })
  goodsFile.value = values
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.error('上传文件数量不能超过10个')
}
/**
 * 捡拾日期改变事件
 */
const handlerPickDateChange = () => {
  addForm.goodsLimitTime = ''
  if (addForm.pickUpTime) {
    let unit: any = 'hour'
    if (addForm.timeLimitUnit === 'Y') {
      unit = 'year'
    } else if (addForm.timeLimitUnit === 'D') {
      unit = 'day'
    }
    addForm.goodsLimitTime = dayjs(addForm.pickUpTime).add(addForm.timeLimit, unit).format('YYYY-MM-DD HH:mm:ss')
  }
}

/**
 * 物品类型改变事件
 */
const handlerGoodsTypeChange = (row: any) => {
  const data = {}
  for (const item of props.goodsType) {
    if (item.typeId === row) {
      data = item
      break
    }
  }
  disabled.value = false
  if (data.goodsType !== '一般物品') disabled.value = true
  addForm.timeLimitUnit = data.timeLimitUnit
  addForm.timeLimit = data.timeLimit
  if (addForm.pickUpTime) {
    let unit: any = 'hour'
    if (addForm.timeLimitUnit === 'Y') {
      unit = 'year'
    } else if (addForm.timeLimitUnit === 'D') {
      unit = 'day'
    }
    addForm.goodsLimitTime = dayjs(addForm.pickUpTime).add(addForm.timeLimit, unit).format('YYYY-MM-DD HH:mm:ss')
  }
}

// 上传前
const handlerBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
  const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const whiteList = ['jpg', 'png', 'JPG', 'PNG']
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error('上传文件类型只能是 jpg,png格式')
    return false
  }
  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小只能在10M以内')
    return false
  }
}

// 上传成功
const handlerUploadSuccess: UploadProps['onSuccess'] = (resp, uploadFile, uploadFiles) => {
  console.log(resp, uploadFile, uploadFiles)
  if (resp.code === '1') {
    const item: FileFace = {
      enclosureContent: resp.data.enclosureCode,
      enclosureName: resp.data.enclosureName,
      enclosureSuffix: resp.data.enclosureSuffix,
      resourceAddress: resp.data.resourceAddress,
      enclosureCode: resp.data.enclosureCode
    }
    goodsFile.value.push(item)
    if (goodsFile.value.length >= 10) {
      hideUpload.value = true
    }
  }
}

const handlerUploadError: UploadProps['onError'] = (error, uploadFile, uploadFiles) => {
  console.log(error, uploadFile, uploadFiles)
}

const delFile = (code: string) => {
  deleteFile(code).then(res => {
    console.log(res)
  })
}

/**
 * 取消
 */
const handlerCancel = () => {
  uploadRef.value?.clearFiles()
  emit('cancel')
}

/**
 * 提交
 */
const handlerAddSubmit = async (formEl: FormInstance | undefined) => {
  loading.value = true
  if (!formEl) {
    loading.value = false
    return
  }
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      addForm.pickUpTime = addForm.pickUpTime ? dayjs(addForm.pickUpTime).format('YYYY-MM-DD HH:mm:ss') : ''
      const payload: AppendGoodsItem = { ...addForm }
      payload.creator = {
        id: userInfo.value.userId,
        name: userInfo.value.name,
        organId: userInfo.value.organId,
        organName: userInfo.value.organName
      }
      payload.files = goodsFile.value
      payload.terminal = addForm.depositTerminal
      console.log(payload)
      const res: any = await pickUpGoodsAppend(payload)

      if (res?.code === '1') {
        ElMessage.success('新增成功！')
        addGoodsFormRef.value?.resetFields()
        uploadRef.value?.clearFiles()
        goodsFile.value = []
        hideUpload.value = false
        emit('submit')
      } else {
        ElMessage.error(res?.message || '新增失败，请重试！')
      }
      console.log('Submit!')
    } else {
      console.log('error submit!', fields)
    }
    loading.value = false
  })
}
watch(
  () => props.visible,
  (val) => {
    if (val) {
      uploadRef.value?.clearFiles()
      addGoodsFormRef.value?.resetFields()
      goodsFile.value = []
      hideUpload.value = false
    }
  }
)
</script>

<style lang="less" scoped>
.upload-img {
  width: 100%;
}
/deep/.el-form-item__content {
  width: 192px;
}
.buttonCancel {
  width: 88px;
}
.el-content-width {
  width: 192px;
}
.buttonReceive {
  width: 88px;
  color: #FFF;
  background: #337FCC;
  border-radius: 6px;
  border: 1px solid #337FCC;
}
.hide {
  /deep/  .el-upload--picture-card {
    display: none;
  }
  /deep/ .el-list-enter-active,.el-list-leave-active {
    transition: all 0s;
  }
  /deep/ .el-list-enter,.el-list-leave-active {
    opacity: 0;
    transform: translateY(0);
  }
}
</style>
